<template>
  <div class="insid_page">
    <header class="return_box">
      <iconpark-icon class="close" icon-id="back" size="1.2rem" @click="router.push('/')"></iconpark-icon>
      <!-- <ImgT src="/imgs/home/return.png" style="width: 24px;height: 24px;" alt="" @click="router.push({
        name: 'home',
      })" /> -->
      <span>
        {{ getHaderText() }}
      </span>
      <div v-if="showMoney" class="money_box">
        <iconpark-icon name="dong1" size="14" />
        <span> {{ roleInfo.money }}</span>
        <iconpark-icon name="add" size="14" @click="router.push('/deposit')" />
      </div>
    </header>

    <nut-searchbar class="search_input" :placeholder="t('inside_page_search_placeholder')" v-model="searchVal"
      @change="onClickSearch" shape="square" background="transparent" input-background="#1D1C3C">
      <template #leftin>
        <iconpark-icon name="sousuo" style="margin-right: 14px;" size="14" />
      </template>
    </nut-searchbar>

    <div class="game_list_cantent">
      <!-- 搜索游戏 -->
      <div v-if="route.query.type === 'search'" class="custom_tab">
        <nut-tabs :auto-height="true" v-model="activeSearchCollect" v-if="searchValFalg" @change="changeLableTab">
          <nut-tab-pane :title="t('inside_page_search_result')" :pane-key="1">
            <div class="electronic_list">
              <ul class="electronic_list_ul" v-if="result.searList.length">
                <li class="electronic_list_li"  v-for="ele in result.searList" :key="ele.id" @click="toGameDetail(ele)">
                  <ImgT class="bg_img" :src="settings.backend_upload + ele.gamePictureH5" alt="" />
                  <div class="name">
                    <span>{{ unserialize(ele.name, true) }}</span>
                  </div>
                  <iconpark-icon v-if="hasLogin" class="collect_img"
                                 :name="allCollected.includes(ele.id) ? 'shoucang-sel' : 'shoucang-def'" size="1rem"
                                 @click.stop="reqCollect(ele, allCollected)"></iconpark-icon>

                </li>
              </ul>
              <EmptyState v-else :text="t('inside_page_no_null_data')" />
            </div>

          </nut-tab-pane>
          <nut-tab-pane :title="t('inside_page_search_hot_games')" :pane-key="2">
            <div class="electronic_list">
              <template v-if="result.searList.length">
                <ul class="electronic_list_ul">
                  <li class="electronic_list_li" @click="toGameDetail(ele)" v-for="ele in result.searList" :key="ele.id">
                    <ImgT class="bg_img" :src="settings.backend_upload + ele.gamePictureH5" alt="" />
                    <div class="name">
                      <span>{{ unserialize(ele.name, true) }}</span>
                    </div>
                    <iconpark-icon v-if="hasLogin" class="collect_img"
                                   :name="allCollected.includes(ele.id) ? 'shoucang-sel' : 'shoucang-def'" size="1rem"
                                   @click.stop="reqCollect(ele, allCollected)"></iconpark-icon>                    <div v-if="ele.is_open" class="masking_layer">
                      <iconpark-icon class="maskin_img" name="padlock1" size="28" />
                      <span>{{ t('inside_page_game_coming_soon') }}</span>
                      <span>{{ t('inside_page_game_stay_tuned') }}</span>
                    </div>
                  </li>
                </ul>
              </template>
              <EmptyState v-else :text="t('inside_page_no_null_data')" />
            </div>
          </nut-tab-pane>
          <nut-tab-pane :title="t('inside_page_search_recent_games')" :pane-key="3">

            <div class="electronic_list">
              <ul class="electronic_list_ul" v-if="result.searList.length">
                <li class="electronic_list_li" @click="toGameDetail(ele)" v-for="ele in result.searList" :key="ele.id">
                  <ImgT class="bg_img" :src="settings.backend_upload + ele.gamePictureH5" alt="" />
                  <div class="name">
                    <span>{{ unserialize(ele.name, true) }}</span>
                  </div>
                  <iconpark-icon v-if="hasLogin" class="collect_img"
                                 :name="allCollected.includes(ele.id) ? 'shoucang-sel' : 'shoucang-def'" size="1rem"
                                 @click.stop="reqCollect(ele, allCollected)"></iconpark-icon>

                </li>
              </ul>
              <EmptyState v-else :text="t('inside_page_no_null_data')" />

            </div>
          </nut-tab-pane>
          <nut-tab-pane :title="t('inside_page_game_category_collect')" :pane-key="4" v-if="hasLogin">

            <div class="electronic_list">
              <ul class="electronic_list_ul" v-if="result.searList.length">
                <li class="electronic_list_li" @click="toGameDetail(ele)" v-for="ele in result.searList" :key="ele.id">
                  <ImgT class="bg_img" :src="settings.backend_upload + ele.gamePictureH5" alt="" />
                  <div class="name">
                    <span>{{ unserialize(ele.name, true) }}</span>
                  </div>
                  <iconpark-icon class="collect_img" v-if="hasLogin"
                                 :name="'shoucang-sel'" size="1rem"
                                 @click.stop="reqCollectPage(ele, 1)"></iconpark-icon>

                </li>
              </ul>
              <EmptyState v-else :text="t('inside_page_no_null_data')" />

            </div>

          </nut-tab-pane>
        </nut-tabs>

      </div>
      <!-- 收藏 -->
      <div v-if="route.query.type === 'collect'" class="custom_tab">
        <nut-tabs v-model="activeSearchCollect" @change="changeLableTab">
          <nut-tab-pane :title="t('inside_page_tab_all')" :pane-key="4">
            <div class="electronic_list">
              <ul class="electronic_list_ul" v-if="result.searList.length">
                <li class="electronic_list_li" @click="toGameDetail(ele)" v-for="ele in result.searList" :key="ele.id">
                  <ImgT class="bg_img" :src="settings.backend_upload + ele.gamePictureH5" alt="" />
                  <div class="name">
                    <span>{{ unserialize(ele.name, true) }}</span>
                  </div>
                  <iconpark-icon class="collect_img" v-if="hasLogin"
                                 :name="'shoucang-sel'" size="1rem"
                                 @click.stop="reqCollectPage(ele, 1)"></iconpark-icon>
                </li>
              </ul>
              <EmptyState v-else :text="t('inside_page_no_null_data')" />
            </div>
          </nut-tab-pane>
          <nut-tab-pane :title="t('inside_page_search_recent_games')" :pane-key="3">
            <div class="electronic_list">
              <ul class="electronic_list_ul" v-if="collectRecentData().length">
                <li class="electronic_list_li" @click="toGameDetail(ele)" v-for="ele in collectRecentData()" :key="ele.id">
                  <ImgT class="bg_img" :src="settings.backend_upload + ele.gamePictureH5" alt="" />
                  <div class="name">
                    <span>{{ unserialize(ele.name, true) }}</span>
                  </div>
                  <iconpark-icon class="collect_img" v-if="hasLogin"
                                 :name="'shoucang-sel'" size="1rem"
                                 @click.stop="reqCollectPageCollectRecent(ele, 1)"></iconpark-icon>
<!--                  <iconpark-icon v-if="hasLogin" class="collect_img"-->
<!--                                 :name="allCollected.includes(ele.id) ? 'shoucang-sel' : 'shoucang-def'" size="1rem"-->
<!--                                 @click.stop="reqCollect(ele, allCollected)"></iconpark-icon>-->
                </li>
              </ul>
              <EmptyState v-else :text="t('inside_page_no_null_data')" />
            </div>
          </nut-tab-pane>
        </nut-tabs>
      </div>




      <!--   热门推荐   -->
      <div v-if="(route.query.type === 'search' && hotDataVal.length)" class="electronic_list hotList">
        <div class="title">
          <img src="/imgs/home/0.webp" alt="">
          <span>{{ t('inside_page_game_category_hot_recommended') }}</span>
        </div>
        <ul class="electronic_list_ul">
          <li class="electronic_list_li" @click="toGameDetail(ele)" v-for="ele in hotDataVal" :key="ele.id">
            <ImgT class="bg_img" :src="`${settings.backend_upload}${ele.picture_h5}`" alt="" />
            <div class="name">
              <span>{{ unserialize(ele.name, false) }}</span>
            </div>
            <iconpark-icon class="collect_img" v-if="hasLogin"
                           :name="allCollected.includes(ele.id) ? 'shoucang-sel' : 'shoucang-def'" size="1rem"
                           @click.stop="reqCollect(ele, allCollected)"></iconpark-icon>
            <div v-if="ele.is_maintain === 1" class="masking_layer">
              <iconpark-icon class="maskin_img" name="padlock1" size="28" />
              <span>{{ t('inside_page_game_coming_soon') }}</span>
              <span>{{ t('inside_page_game_stay_tuned') }}</span>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>

</template>
<script setup lang="ts">
import pinia from '@/store';
import {Page} from '@/store/page';
import {User} from '@/store/user';
import {storeToRefs} from 'pinia';
import H5Websocket from "@/net/Net1";
import {onBeforeMount, onMounted, reactive, ref} from 'vue';
import {useRoute, useRouter} from "vue-router";
import {NetPacket} from '@/netBase/NetPacket';
import {useI18n} from 'vue-i18n';
import EmptyState from './components/EmptyState.vue'
import {MessageEvent2} from '@/net/MessageEvent2';
import {NetMsgType} from '@/netBase/NetMsgType';
import {onPlayGame, unserialize} from "../../utils/useStoreMethods.ts";

import {Local} from "@/utils/storage";
import {reqCollect} from '@/utils/useNetMethods';


const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const {
  lang,
  settings,
  homeGameData
} = storeToRefs(Page(pinia));

const { allCollected, roleInfo, hasLogin } = storeToRefs(User(pinia));


const searchVal = ref('')
const searchValFalg = ref(false)
const activeSearchCollect = ref<number>(1)

const hotGameSliceData = ref<any[]>([])
const gameType = ref(false)
const showMoney = ref(false)

const state = reactive({
  // 游戏平台id  -1为查看全部的游戏
  agentId: -1,

  // 自定义标签 0为全部 1为热门 -2为收藏，-3为最近
  lableId: 0,

  // //也表示场馆id -1 为所有场馆
  kindId: -1,


  // 游戏输入框节流
  timer: null as any,

})

const params: any = reactive({ // 参数
  isLoad: false,
  loadMore: true,
  pageSize: 15,
  page: 1,
})


const result: any = reactive({ // 结果
  total_page: 0,
  // 游戏集合
  list: [],
  searList: []
})

// 判读是否是进入游戏二级页或者直接进入游戏
const toGameDetail = async (item: any) => {
  console.log(item);
  if (item.has_next == 1) {
    // 跳转二级页面
    router.push({
      path: 'gameDetail',
      query: {
        agent_id: item.id,
        venue_id: item.three_game_kind[0].id,
        name: item.name[lang.value].toUpperCase(),
      }
    })
  } else {
    onPlayGame(item)

  }
}

const onClickSearch = () => {
  if (!searchVal.value) {
    return result.searList = result.list
  }
  searchValFalg.value = true

  // 修改搜索逻辑，处理所有标签页的搜索
  if (route.query.type === 'search') {
    if (activeSearchCollect.value === 1) {
      // 搜索结果标签 - 发送网络请求搜索
      getGameList({ value: searchVal.value, type: activeSearchCollect.value, name: route.query.type })
    } else {
      // 其他标签 - 本地过滤
      result.searList = result.list.filter((item: any) => {
        return unserialize(item.name, true).toLowerCase().includes(searchVal.value.toLowerCase())
      })
    }
  } else if (route.query.type === 'collect') {
    // 收藏页面的搜索
    result.searList = result.list.filter((item: any) => {
      return unserialize(item.name, true).toLowerCase().includes(searchVal.value.toLowerCase())
    })
  }
}


const getHaderText = () => {
  const type: any = route.query.type
  showMoney.value = !['search', 'collect', 'hot'].includes(type)
  gameType.value = ['search', 'collect', 'hot', 'video', 'sports', 'lottery'].includes(type)

  const textMap: Record<string, string> = {
    search: 'inside_page_search',
    collect: 'inside_page_collect',
    hot: 'inside_page_hot',
    electronic: 'inside_page_electronic',
    video: 'inside_page_video',
    fishing: 'inside_page_fishing',
    sports: 'inside_page_sports',
    poker: 'inside_page_poker',
    lottery: 'inside_page_lottery'
  }

  return textMap[type] ? t(textMap[type]) : route.query.name
}

// 热门游戏数据
const hotDataVal: any = ref([])

// 获取热门推荐
const getHotData = () => {
  // 直接获取热门游戏数据
  if (homeGameData.value?.length) {
    const hotGames = homeGameData.value.find((e: any) => e.id === 0)?.three_platform || []
    hotGameSliceData.value = hotGames
    hotDataVal.value = hotGames
  }
}


const resetData = () => {
  params.page = 1
  params.pageSize = 15
  result.list = []
  result.searList = []
  result.total_page = 0
}

const queryData = () => { // 查询
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_get_games_in_platform, handleGames); // 热门 收藏 最近 - 有分页

  const query = NetPacket.req_get_games_in_platform()
  query.agentId = state.agentId
  query.kindId = state.kindId
  query.lableId = state.lableId
  query.page = params.page
  query.pageSize = params.pageSize
  H5Websocket.sendMessageHandler(query);
}

//切换上方标签事件
const changeLableTab = (item: any) => {
  // item.paneKey 2-热门 3-最近 4-收藏
  searchVal.value = ''

  // // 自定义标签 0为全部 1为热门 -2为收藏，-3为最近
  state.lableId = item.paneKey === '2' ? 1 : item.paneKey === '3' ? -3 : item.paneKey === '4' ? -2 : 0
  resetData()
  queryData()
}

// 收藏游戏
const collectData = ref([])
const collectRecentData = () => {


  return result.searList.filter((item: any) => {
    return collectData.value.includes(item.id as never)
  })
}

const handleGames = (res: any) => {
  if (route.query.type === 'collect' && state.lableId === -2) {
    collectData.value = res.info.map((item: any) => item.id)
  }
  result.list = res.info
  result.searList = res.info

  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_get_games_in_platform, null); // 热门 收藏 最近

}

const handleQuery = (res: any) => {

  result.list = res.info
  result.searList = res.info
  result.total_page = res.total

  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_look_for_game_name, null); //搜索游戏-有分页

}

// 获取游戏数据（全部类型）
const getGameList = (params: any) => {



  const { value, type, name } = params


  if (name === 'search' && type === 1) {
    if (state.timer != null) {
      clearTimeout(state.timer)
    }
    state.timer = setTimeout(() => {
      MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_look_for_game_name, handleQuery); //搜索游戏

      let tb = NetPacket.req_look_for_game_name()
      tb.agentId = state.agentId;
      tb.kindId = state.kindId;
      tb.name = value
      H5Websocket.sendMessageHandler(tb)
    }, 500);
  }

}

// 添加取消收藏
 const reqCollectPage = async (game: any, id: number) => {
  const query = NetPacket.req_modify_collect()
  query.agentId = game.agentId || game.id  //id 为厂商游戏  例如 体育 真人之类
  query.id = game.id
  query.type = id
  Local.set('gameId', 'COLLECT_CANCEL')
  H5Websocket.sendMessageHandler(query);
   queryData()
}

// 收藏添加游戏
const reqCollectPageCollectRecent = async (game: any, id: number) => {
  const query = NetPacket.req_modify_collect()
  query.agentId = game.agentId || game.id  //id 为厂商游戏  例如 体育 真人之类
  query.id = game.id
  query.type = id
  state.lableId = -2
  Local.set('gameId', 'COLLECT_CANCEL')
  H5Websocket.sendMessageHandler(query);

  collectData.value = collectData.value.filter((item: any) => item !== game.id)
  console.log(collectData.value, '-collectData.value-');
  collectRecentData()
}



onBeforeMount(() => {
  // getCollectGame(-2)
  if (route.query.type === 'collect') {
    activeSearchCollect.value = 4
    state.lableId = -2
    queryData()
  }

})

onMounted(() => {
  getHotData()
})

</script>
<style lang="scss" scoped>
.insid_page {
  --primary-color: #5B6CFF;
  --border-color: #501dc0;
  --bg-color: #131232;

  display: flex;
  flex-direction: column;
  overflow: auto;

  .return_box {
    padding: 14px;
    position: relative;
    text-align: center;
    display: grid;
    grid-template-columns: 1fr 10fr 1fr;
    font-family: PingFang SC;
    font-size: 16px;
    font-weight: 500;
    line-height: 24px;
    color: #FFFFFF;

    .money_box {
      position: absolute;
      right: 14px;
      top: 14px;
      height: 28px;
      padding: 6px 8px 6px 6px;
      opacity: 0;
      border-radius: 14px;
      background: #1D1C48;
      display: flex;
      justify-content: space-between;
      align-items: center;

      span {
        margin: 0 6px;
      }
    }
  }

  .search_input {

    :deep(.square) {
      border-radius: 8px;
    }
  }

  .header_tabs {
    padding: 0 14px;
    display: flex;
    justify-content: space-between;

    .all_box {
      width: 60px;
      height: 40px;
      color: #FFFFFF;
      line-height: 40px;
      text-align: center;
      margin-bottom: 8px;
      border-radius: 8px;
      background: #131232;
    }

    .active {
      background: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);
    }

    .custom_tab {
      width: calc(100vw - 102px);
    }
  }

  .custom_tab {
    width: 100%;

    .custom_tab_ul {
      width: 100%;
      height: 44px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      overflow: auto;

      .search_li_box {
        width: 25%;
      }

      .shoucang_box {
        width: 50%;
      }

      .custom_tab_li {
        height: 80%;
        font-family: PingFang SC;
        font-size: 14px;
        font-weight: 500;
        line-height: 14px;

        .custom_tab_item {
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }

      .custom_tab_item_active {
        color: var(--primary-color);
        position: relative;

        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          height: 3px;
          background: var(--border-color);
        }
      }

    }
  }

  .game_list_cantent {
    height: calc(100vh - 175px);
    overflow: auto;
    padding: 0 14px;

    .hot_top_tab {
      width: 100%;
      position: relative;
      display: flex;
      justify-content: space-between;
      align-items: center;
      overflow: hidden;

      .custom_tab_ul {
        width: 100%;
        height: 34px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        white-space: nowrap;
        overflow-x: auto;

        .custom_tab_li {
          margin-right: 12px;
          height: 80%;
          font-family: PingFang SC;
          font-size: 14px;
          font-weight: 500;
          line-height: 14px;
          text-align: left;

          .custom_tab_item {
            height: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
          }
        }

        .custom_tab_item_active {
          color: var(--primary-color);
          position: relative;

          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 3px;
            background: var(--border-color);
          }
        }

      }

      .right_menu {
        display: flex;
        justify-content: center;
        align-items: center;

      }
    }

    .electronic_list {
      min-height: 200px;
      overflow: hidden;

      .electronic_list_ul {
        max-height: 100%;
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        grid-column-gap: 6px;
        overflow: auto;
        margin-top: 8PX;

        .electronic_list_li {
          position: relative;
          height: 148px;
          position: relative;
          box-sizing: border-box;
          margin-bottom: 6px;
          .name {
            display: flex;
            align-items: center;
            justify-content: center;
            position: absolute;
            border-radius: 0 0 8px 8px !important;
            left: 0;
            bottom: 0 !important;
            width: 100%;
            height: 36px;
            background-color: rgba(26, 25, 68, 1);

            span {
              text-align: center;
              font-family: PingFang SC;
              font-size: 14px;
              font-weight: 600;

            }
          }

          .bg_img {
            position: absolute;
            width: 100%;
            // height: 100%;
            top: 0;
            left: 0;
          }

          .name {
            width: 100%;
            font-family: PingFang SC;
            font-size: 12px;
            font-weight: 600;
            line-height: 12px;
            color: #FFFFFF;
            position: absolute;
            left: 0px;
            bottom: 8px;
            text-align: center;
            //white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .collect_img {
            position: absolute;
            top: 6px;
            right: 6px;
          }

        }

        .masking_layer {
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          backdrop-filter: blur(1px);
          background: rgba(0, 0, 0, 0.6);
          font-family: PingFang SC;
          font-size: 12px;
          font-weight: 500;
          line-height: 18px;
          color: #ffffff;

          .maskin_img {
            width: 32px;
            height: 32px;
            margin-bottom: 8px;
          }
        }
      }
    }

    .hotList {
      .title {
        font-family: PingFang SC;
        font-size: 14px;
        font-weight: 600;
        color: #fff;
        margin-bottom: 15px;

        img {
          margin-right: 4px;
          width: 20px;
        }
      }

      .electronic_list_li {
        width: 112px;
        height: 148px;
      }
    }

    .venue_game_box {
      min-height: 200px;
      height: 100%;


      :deep(.nut-tabs__titles) {
        width: 60px;
        padding: 0;
        margin: 0;
        background: transparent !important;
        border: none !important;
        box-shadow: none !important;
        border-radius: 0 !important;

        .custom-tab-item {
          background: #131232;
          margin-bottom: 8px;
          border-radius: 8px;
        }

        .active {
          background: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);
        }

        img {
          width: 60px;
          height: 40px;
        }
      }

      .right_electronic_list_ul {
        padding-left: 14px;
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        grid-column-gap: 8px;
        overflow: auto;
        margin-top: 8PX;

        .right_electronic_list_li {
          height: 110px;
          position: relative;
          box-sizing: border-box;
          margin-bottom: 8px;

          .bg_img {
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
          }

          .name {
            width: 100%;
            font-family: PingFang SC;
            font-size: 12px;
            font-weight: 600;
            line-height: 12px;
            color: #FFFFFF;
            position: absolute;
            left: 0px;
            bottom: 8px;
            text-align: center;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .collect_img {
            position: absolute;
            top: 6px;
            right: 6px;
          }

        }

        .masking_layer {
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          backdrop-filter: blur(1px);
          background: rgba(0, 0, 0, 0.6);
          font-family: PingFang SC;
          font-size: 12px;
          font-weight: 500;
          line-height: 18px;
          color: #ffffff;

          .maskin_img {
            width: 32px;
            height: 32px;
            margin-bottom: 8px;
          }
        }
      }
    }
  }
}

:deep(.nut-tabs) {
  .nut-tabs__titles {
    background: transparent;
    border: none;

    .nut-tabs__titles-item {
      color: #fff;
      font-size: 14px;
      padding: 0 12px;

      &.active {
        color: var(--primary-color);
        font-weight: 600;

        &::after {
          background: var(--border-color);
        }
      }
    }
  }
}
</style>
